const Category = require('../models/Category');
const db = require('../config/db');

class CategoryController {
  // Get all categories for a user
  static async getCategories(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      
      // Get categories (both default and user-specific)
      const result = await db.query(
        `SELECT * FROM categories WHERE user_id = 0 OR user_id = $1 ORDER BY type, name`,
        [user_id]
      );
      
      const categories = result.rows.map(row => Category.fromRow(row));
      
      res.json({
        categories: categories.map(category => category.toJSON())
      });
    } catch (error) {
      console.error('Get categories error:', error);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
  
  // Create a new category
  static async createCategory(req, res) {
    try {
      const { name, type, icon, color } = req.body;
      const user_id = req.userId; // Set by auth middleware
      
      // Create category
      const result = await db.query(
        `INSERT INTO categories (user_id, name, type, icon, color, is_default) 
         VALUES ($1, $2, $3, $4, $5, FALSE) RETURNING *`,
        [user_id, name, type, icon, color]
      );
      
      const category = Category.fromRow(result.rows[0]);
      
      res.status(201).json({
        message: 'Category created successfully',
        category: category.toJSON()
      });
    } catch (error) {
      console.error('Create category error:', error);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
  
  // Update a category
  static async updateCategory(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      const category_id = parseInt(req.params.id);
      const { name, type, icon, color } = req.body;
      
      // Check if category exists and belongs to user (or is a default category)
      const existingCategory = await db.query(
        `SELECT * FROM categories WHERE id = $1 AND (user_id = $2 OR user_id = 0)`,
        [category_id, user_id]
      );
      
      if (existingCategory.rows.length === 0) {
        return res.status(404).json({ error: 'Category not found' });
      }
      
      // Check if it's a default category
      if (existingCategory.rows[0].user_id === 0) {
        return res.status(400).json({ error: 'Cannot modify default categories' });
      }
      
      // Update category
      const result = await db.query(
        `UPDATE categories SET name = $1, type = $2, icon = $3, color = $4
         WHERE id = $5 AND user_id = $6 RETURNING *`,
        [name, type, icon, color, category_id, user_id]
      );
      
      if (result.rows.length === 0) {
        return res.status(404).json({ error: 'Category not found' });
      }
      
      const category = Category.fromRow(result.rows[0]);
      
      res.json({
        message: 'Category updated successfully',
        category: category.toJSON()
      });
    } catch (error) {
      console.error('Update category error:', error);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
  
  // Delete a category
  static async deleteCategory(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      const category_id = parseInt(req.params.id);
      
      // Check if category exists and belongs to user
      const existingCategory = await db.query(
        `SELECT * FROM categories WHERE id = $1 AND user_id = $2`,
        [category_id, user_id]
      );
      
      if (existingCategory.rows.length === 0) {
        return res.status(404).json({ error: 'Category not found' });
      }
      
      // Check if there are bills associated with this category
      const billCountResult = await db.query(
        `SELECT COUNT(*) FROM bills WHERE category_id = $1 AND user_id = $2`,
        [category_id, user_id]
      );
      
      const billCount = parseInt(billCountResult.rows[0].count);
      
      if (billCount > 0) {
        return res.status(400).json({ 
          error: 'Cannot delete category with associated bills. Please reassign bills first.' 
        });
      }
      
      // Delete category
      await db.query(
        `DELETE FROM categories WHERE id = $1 AND user_id = $2`,
        [category_id, user_id]
      );
      
      res.json({
        message: 'Category deleted successfully'
      });
    } catch (error) {
      console.error('Delete category error:', error);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
}

module.exports = CategoryController;